package com.yvan.codeslave.action;

import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.xml.XmlFileImpl;
import com.yvan.codeslave.PluginUtils;
import com.yvan.platform.FileUtils;
import lombok.val;
import lombok.var;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class ModulePopActions extends ActionGroup {
    /**
     * 是否不存在子菜单
     */
    private boolean notExistsChildren;

    @NotNull
    @Override
    public AnAction[] getChildren(@Nullable AnActionEvent event) {
        Project project = getEventProject(event);
        if (project == null) {
            return getEmptyAnAction();
        }

        //获取选中的PSI元素
        PsiElement psiElement = event.getData(LangDataKeys.PSI_ELEMENT);

        if (psiElement instanceof XmlFileImpl) {
            XmlFileImpl xmlFile = (XmlFileImpl) psiElement;
            val vfile = xmlFile.getVirtualFile();
            var state = PluginUtils.getState();
            if (state != null) {
                val ft = FileUtils.normalizePath(vfile.getPath());
                val fb = FileUtils.normalizePath(state.basePath);
                if (ft.startsWith(fb)) {
                    PluginUtils.moduleFile = xmlFile;
                    return new AnAction[]{
                            new BuildCodeAction()
                    };
                }
            }
        }

        return getEmptyAnAction();
    }

    /**
     * 获取空菜单组
     *
     * @return 空菜单组
     */
    private AnAction[] getEmptyAnAction() {
        this.notExistsChildren = true;
        return AnAction.EMPTY_ARRAY;
    }
}
